/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: InitDataSource.java</p>
 *
 * @author zz
 * @date 2024/2/4
 * @version 1.0
 * History:
 * v1.0.0 2024/2/4 Create
 */
package com.sqlweb.sqlweb.config;

import cn.hutool.core.collection.CollectionUtil;
import com.sqlweb.sqlweb.entity.DataSourceConfig;
import com.sqlweb.sqlweb.mapper.DataSourceConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

/**
 * <p>Title: InitDataSource</p>
 * <p>Description: </p>
 *
 * @author zz
 */
@Component
@Slf4j
public class InitDataSource implements CommandLineRunner {
    @Autowired
    private DynamicDataSourceConfig dynamicDataSourceConfig;
    @Autowired
    private DataSourceConfigMapper dataSourceConfigMapper;

    @Override
    public void run(String... args) throws Exception {
        log.info("数据源初始化");
        try {
            List<DataSourceConfig> allConfigs = dataSourceConfigMapper.selectAll();
            if (!CollectionUtil.isEmpty(allConfigs)) {
                allConfigs.forEach(dataSourceConfig -> {
                    DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
                    dataSourceBuilder.url(dataSourceConfig.getJdbcUrl())
                            .username(dataSourceConfig.getUsername())
                            .password(dataSourceConfig.getPassword())
                            .driverClassName(dataSourceConfig.getDriverClassName());
                    DataSource dataSource = dataSourceBuilder.build();
                    dynamicDataSourceConfig.addDataSource(dataSourceConfig.getId(), dataSource);
                });
            }
        } catch (Exception e) {
            log.error("初始化失败:" + e);
        }
    }
}
